<template>
  <div>
    <!-- 列表 -->
    <a-table
      :columns="columns"
      :data-source="list"
      bordered
      rowKey="key"
      :loading="loading"
      :pagination="pagination"
      @change="handleTableChange"
    >
      <!-- :row-selection="rowSelection" -->
      <template #title><a-button type="primary" @click="add" v-has="{ a: $route, b: 2 }" class="d-a-center">新增</a-button></template>
      <template #faceImg="{ record }">
        <img style="width: 100px; height: 40px" :src="record.faceImg" alt="" />
      </template>
      <template #isRecommend="{ record, index }">
        <div @click="changeStack(record.isRecommend, index, record.id)">
          <a-switch v-model:checked="record.isRecommend" :checkedValue="1" :unCheckedValue="0" />
        </div>
      </template>
      <template #operation="{ record }">
        <!-- <a-button
          type="link"
          @click="handleToTop(record.key)"
          v-has="{ a: $route, b: 2 }"
          >置顶</a-button
        > -->
        <a-button type="link" @click="edit(record, '编辑')" v-has="{ a: $route, b: 2 }">编辑</a-button>
        <a-button type="link" @click="edit(record, '查看')" v-has="{ a: $route, b: 1 }">查看</a-button>
        <a-button type="link" danger @click="del(record.key)" v-has="{ a: $route, b: 2 }">删除</a-button>
      </template>
    </a-table>
    <!-- 多项删除 -->
    <!-- <a-button type="danger" @click="listDel">删除</a-button> -->

    <div>
      <!-- 知识库详情弹窗 -->
      <a-modal
        v-if="visible"
        :visible="visible"
        :title="modalTitle"
        @cancel="closeModal('visible')"
        width="70%"
        height="1000px"
        :maskClosable="false"
      >
        <template v-slot:footer>
          <div class="d-j-around">
            <a-button @click="closeModal('visible')" class="d-a-center">关闭</a-button>
            <a-button v-if="modalTitle != '查看'" type="primary" @click="addArticle" class="d-a-center">确定</a-button>
          </div>
        </template>

        <a-form :model="form" :rules="rules" :labelCol="labelCol" ref="formRef">
          <a-form-item label="标题" name="title">
            <a-input placeholder="请输入标题" :disabled="modalTitle == '查看'" v-model:value="form.title" allow-clear></a-input>
          </a-form-item>
          <a-form-item label="发布日期" name="pushTime">
            <a-date-picker
              :disabled-date="disabledDate"
              :disabled="modalTitle != '新增'"
              valueFormat="YYYY-MM-DD"
              v-model:value="form.pushTime"
            />
          </a-form-item>
          <a-col :span="12">
            <a-form-item label="新闻封面" name="titleImgPath">
              <a-upload
                v-model:file-list="titleImgPath"
                list-type="picture-card"
                class="avatar-uploader"
                :maxCount="1"
                :customRequest="uploadDetail_image"
                :disabled="modalTitle == '查看'"
              >
                <div v-if="titleImgPath.length < 1" class="ant-upload-text">
                  <plus-outlined />
                </div>
              </a-upload>
              图片尺寸：260*180
            </a-form-item>
          </a-col>

          <a-col :span="24">
            <a-form-item label="内容" style="width: 100%; height: 360px !important">
              <div id="wangeditor" style="width: 100%; height: 360px !important">
                <div ref="editorElem" style="width: 100%; height: 100px !important"></div>
              </div>
            </a-form-item>
          </a-col>
        </a-form>
      </a-modal>
    </div>
    <a-modal :visible="sortShow" :footer="null" width="90%" @cancel="cancel1">
      <a-table :columns="sortColums" :data-source="sortList" bordered :customRow="customRow1"> </a-table>
      <a-row>
        <a-col :span="4" :offset="6">
          <a-button type="primary" size="large" @click="cancel1">关闭</a-button>
        </a-col>
        <a-col :span="4" :offset="2">
          <a-button type="primary" size="large" @click="handleSave">保存</a-button>
        </a-col>
      </a-row>
    </a-modal>
  </div>
</template>
<script>
import E from 'wangeditor'
import { url } from '@/utils/options'

import { reactive, ref, computed, createVNode, watch, toRefs, unref, toRaw, isReactive, toRef, shallowRef, onMounted } from 'vue'
import moment from 'moment'
import { publish, swiperType } from '@/utils/dict.js'
import { CheckOutlined, EditOutlined, ExclamationCircleOutlined, QuestionCircleOutlined } from '@ant-design/icons-vue'
import { uploadPicture } from '@/api/service/index.js'
import { Modal, message } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import * as api from '@/api/content/news.js'
import { selectAllService, selectAllType } from '@/api/service/index.js'
import { deleteObjBlank } from '@/assets/js/common.js'
import { useModal } from '@/hooks'

export default {
  setup() {
    const editorElem = ref(null)
    const searchRef = ref('')
    const formRef = ref('')
    let change1 = null // 源目标数据序号
    let changeObj = null // 源目标数据序号
    let change2 = null
    const data = reactive({
      sortShow: false,
      sortList: [],
      editor: '',
      info: '',
      flag: false,
      list: [],
      loading: true,
      visible: false,
      serviceList: [], //分类列表
      detaiList: [],
      consumables: [], //默认绑定ID即可
      statusAct: 0,
      searchForm: {},
      typeList: [],
      form: {},
      value: [], //分类-这个远程加载的数据好像不可以哎
      defaultValue: [],
      titleImgPath: [],
      contentImg: [],
      publish,
      swiperType: true ? [...swiperType.splice(0, 1)] : [...swiperType]
    })

    const title = ref('') //分类名称

    const modalTitle = ref('新增')
    const rules = {
      pushTime: [{ required: true, message: '请选择发布日期' }],
      title: [{ required: true, message: '请输入' }],
      // titleImgPath: [{ required: true, message: "请上传",trigger: ["change",'blur']}],
      // contentImg: [{ required: true, message: "请上传" }],
      content: [{ required: true, message: '请输入' }]
      // top:[{ required: true, message: "请选择"}]
    }
    const rules1 = {
      name: [{ required: true, message: '请输入耗材名称!' }],
      sellPrice: [{ required: true, message: '请输入销售价!' }],
      serviceId: [{ required: true, message: '请输入服务类型!' }],
      typeId: [{ required: true, message: '请输入服务分类!' }],
      bazaarPrice: [{ required: true, message: '请输入市场价格!' }],
      bagNumber: [{ required: true, message: '请输入耗材编号!' }]
      // value: [{ required: true, message: "请选择耗材分类!" }],
    }

    // 分页器
    const page = reactive({
      current: 1,
      pageSize: 10,
      total: 0
    })
    const sortColums = [
      {
        title: '拖动排序',
        // dataIndex: "serveName",
        className: 'table',
        align: 'center'
      },
      {
        title: '编号',
        dataIndex: 'id',
        className: 'table',
        align: 'center'
        // slots: {
        //   customRender: "sort",
        // },
      },
      {
        title: '标题',
        dataIndex: 'title',
        className: 'table',
        align: 'center'

        // sorter: (a, b) => a.price - b.price,
      },
      {
        title: '排序',
        dataIndex: 'sortId',
        className: 'table',
        align: 'center'
      }
    ]
    const saleStatusOptions = reactive([
      {
        name: '全部',
        id: ''
      },
      {
        name: '上架',
        id: 0
      },
      {
        name: '下架',
        id: 1
      }
    ])
    const consumeOptions = reactive([
      {
        name: '耗材名称',
        id: 1
      },
      {
        name: '耗材分类',
        id: 1
      }
    ])
    const delListId = ref([]) //删除数组ID集合
    const chooseStatus = (status, index) => {
      data.statusAct = index
      data.searchForm.status = status
      page.current = 1
      init()
    }
    // 查询
    const search = () => {
      page.current = 1
      init()
    }
    const reset = () => {
      data.searchForm = {}
      search()
    }
    const columns = [
      {
        title: '编号',
        dataIndex: 'id',
        className: 'table'
      },
      {
        title: '标题',
        dataIndex: 'title',
        className: 'table',
        maxWidth: 180,
        ellipsis: true
      },
      {
        title: '新闻封面',
        dataIndex: 'faceImg',
        className: 'table',
        slots: {
          customRender: 'faceImg'
        }
      },

      {
        title: '发布人',
        dataIndex: 'publisher',
        className: 'table'
      },
      {
        title: '创建时间',
        dataIndex: 'createdTime',
        className: 'table'
      },
      {
        title: '首页推荐',
        dataIndex: 'isRecommend',
        className: 'table',
        slots: {
          customRender: 'isRecommend'
        }
      },
      {
        title: '操作',
        dataIndex: 'operation',
        className: 'table',
        slots: {
          customRender: 'operation'
        }
      }
    ]

    // 分页器
    const pagination = computed(() => ({
      current: page.current,
      pageSize: page.pageSize,
      pageSizeOptions: ['10', '20', '30'],
      showTotal: (total, range) => {
        return '共' + total + '条'
      },
      total: page.total,
      showQuickJumper: true,
      showSizeChanger: true
    }))

    // 分页器改变的时候
    const handleTableChange = (pagination, filters, sorter) => {
      console.log(pagination, '当前分页')
      page.current = pagination.current
      page.pageSize = pagination.pageSize

      // 请求列表接口
      init()
    }
    const cancel = () => {
      data.visible = false
      title.value = ''
      data.form = { top: 0 }
      data.consumables = []
    }
    const disabledDate = current => {
      // Can not select days before today and today
      return current && current > moment().endOf('day')
    }
    // 新增
    const add = () => {
      modalTitle.value = '新增'
      data.form = { content: '' }
      data.contentImg = []
      data.titleImgPath = []
      data.visible = true
      data.editor = ''
      setTimeout(() => {
        initEditor()
      }, 500)
    }
    const edit = async (item, name = '编辑') => {
      // item.typeId = String(item.typeId);
      console.log(item, 'item')
      data.form = { ...item }
      // data.consumables = item.consumables.map((el) => el.id);
      modalTitle.value = name

      data.titleImgPath = [{ url: item.faceImg, status: 'done' }]
      // data.value[0] = String(item.typeId);
      data.visible = true
      data.editor = ''

      setTimeout(() => {
        initEditor()
        data.editor.txt.html(item.content)
        // data.form.content = item.content
      }, 500)
    }

    const closeModal = e => {
      data[e] = false
      if (e == 'visible') {
        data.titleImgPath = []
        data.form.content = ''
      }
    }
    // 新增
    const addArticle = async () => {
      formRef.value.validate().then(async () => {
        let res = null
        if (data.titleImgPath.length == 0) {
          message.error('请上传列表图！')
          return
        }
        if (data.form.content == '') {
          message.error('请输入新闻内容')
          return
        }
        // titleImgPath列表图
        data.form.faceImg = data.titleImgPath[0].url
        if (data.flag) return
        data.flag = true
        if (!data.form.id) {
          res = await api.addNewsInfomation({ ...data.form })
        } else {
          res = await api.addNewsInfomation({ ...data.form })
        }
        if (res.success) {
          message.success('操作成功')
          init()
          data.flag = false
          closeModal('visible')
        }
      })
    }
    // 置顶
    const handleToTop = async key => {
      let res = await api.newsInfomationOpenRecommend({ id: Number(key) })
      if (res.success) {
        message.success('置顶成功')
        init()
      }
    }
    // 删除
    const del = key => {
      const { closeModal } = useModal.confirm({
        title: () => '你确定删除当前项吗?',
        icon: () => createVNode(QuestionCircleOutlined),
        content: () =>
          createVNode(
            'div',
            {
              style: 'color:red;'
            },
            '删除当前数据后不可恢复，请谨慎考虑。'
          ),
        onOk: async () => {
          let res = await api.deleteNewsInfomation({ id: Number(key) })
          if (res.success) {
            message.success('删除成功')
            init()
            closeModal()
          }
        },
        class: 'test'
      })
    }
    const handleSave = () => {
      let arr = data.sortList.map(m => {
        return { id: m.id }
      })
      api
        .newsInfomationOpenRecommendSave({
          lutuofficialNewsInformationList: [...arr]
        })
        .then(r => {
          if (r.success) {
            message.success('操作成功')
            data.sortShow = false
            init()
          }
        })
    }
    const selectConsume = e => {
      console.log(e)
    }
    const selectService = e => {
      // console.log(e, "服务类型");s
    }
    const selectType = e => {}
    // 上传头图
    const uploadDetail_image = file => {
      uploadImage(file, 'titleImgPath')
    }
    const uploadDetail_imgPath = file => {
      uploadImage(file, 'contentImg')
    }
    // 公共的上传图片
    const uploadImage = async (file, e) => {
      let formData = new FormData()
      formData.append('file', file.file)
      let res = await uploadPicture(formData, 'ali')
      // // url存入列表中,为什么是两个fileList
      data[e] = data[e].filter(el => el.status == 'done')
      if (res.success) {
        data[e].push({
          uid: file.file.uid,
          url: res.object,
          status: 'done',
          name: file.file.name
        })
      }
      console.log(data[e], 'data[e]是--')
    }
    // 全选反选
    const rowSelection = ref({
      checkStrictly: false,
      onChange: (selectedRowKeys, selectedRows) => {
        console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows)
        delListId.value = selectedRowKeys
      },
      onSelect: (record, selected, selectedRows) => {
        //console.log(record, selected, selectedRows,'选择多项');
      },
      onSelectAll: (selected, selectedRows, changeRows) => {
        //console.log(selected, selectedRows, changeRows,'全选操作');
        // 数组项
      }
    })
    // 删除多项

    const cancel1 = () => {
      data.sortShow = false
      data.sortList = []
      init()
    }
    // 是否上下架 就把原来的状态改变下就行，传递下当前项的耗材ID即可，
    const changeStack = async (checked, index, id) => {
      // let check = checked==1 ? 0 : 1
      let res = await api.newsInfomationOpenRecommend({
        id,
        isRecommend: checked
      })
      if (res.success) {
        data.list[index].isRecommend = Number(checked)
        if (checked) {
          data.sortList = [...res.object]
          data.sortShow = true
        }
      } else {
        data.list[index].isRecommend = Number(!checked)
      }
    }
    // initEditor()
    initServiceList()
    init()
    initAllDetailList()
    async function init() {
      let obj = {
        pageNum: page.current,
        pageSize: page.pageSize
      }
      if (data.searchForm) {
        obj.titleOrnumber = data.searchForm.titleOrnumber
      }
      let res = await api.newsInfomationList(obj)
      if (res.success) {
        res.object.list.map(el => (el.key = el.id))
        data.list = res.object.list
        data.loading = false
        page.total = res.object.total
      }
    }
    function initEditor() {
      let baseURL = ''
      if (process.env.VUE_APP_MODE == "'development'") {
        // 本地调试: 记得将vue.config.js中的Proxy注打开
        baseURL = '/api'
      } else {
        // 发布到正式服务器上：记得把vue.config.js中Proxy注释掉
        baseURL = url
      }
      data.editor = new E(editorElem.value) //获取组件并构造编辑器
      // data.editor.config.uploadImgShowBase64 = false; // base 64 存储图片
      data.editor.config.uploadImgServer = baseURL + '/admin/picture/uploadPicture?directoryName=name' // 配置服务器端地址
      // data.editor.config.uploadImgHeaders = {}; // 自定义 header
      data.editor.config.uploadFileName = 'file' // 后端接受上传文件的参数名
      // data.editor.config.uploadImgMaxSize = 2 * 1024 * 1024; // 将图片大小限制为 2M
      // data.editor.config.uploadImgMaxLength = 6; // 限制一次最多上传 3 张图片
      // data.editor.config.uploadImgTimeout = 3 * 60 * 1000; // 设置超时时间
      data.editor.config.uploadImgHooks = {
        fail: (xhr, editor, result) => {
          console.log(result)
          // 插入图片失败回调
        },
        success: (xhr, editor, result) => {
          console.log(result)
        },
        timeout: (xhr, editor) => {
          // 网络超时的回调
        },
        error: (xhr, editor) => {
          console.log(111)
          // 图片上传错误的回调
        },
        customInsert: (insertImg, result, editor) => {
          // 图片上传成功，插入图片的回调
          //result为上传图片成功的时候返回的数据，这里我打印了一下发现后台返回的是data：[{url:"路径的形式"},...]
          //这块一定要细心，因为会影响到上传图片成功之后的回显
          console.log(result, 9999999)
          let url = result.object
          // let url = data.GLOBAL.myhf+result.data
          insertImg(url)
          // }
        }
      }
      data.editor.config.onchange = html => {
        console.log(html)
        data.form.content = html // 绑定当前逐渐地值
      }
      data.editor.create()
    }
    // 二级首页拖拽
    const customRow1 = (record, index) => {
      //  console.log(record, index);// 这里输出是表格全部的数据
      return {
        props: {
          // draggable: 'true'
        },
        style: {
          cursor: 'pointer'
        },
        // 鼠标移入
        onMouseenter: event => {
          // 兼容IE
          var ev = event || window.event
          ev.target.draggable = true // 让你要拖动的行可以拖动，默认不可以
        },
        // 开始拖拽
        onDragstart: event => {
          // 兼容IE
          var ev = event || window.event
          // 阻止冒泡
          ev.stopPropagation()
          // 得到源目标数据序号
          change1 = index
          changeObj = record
          console.log(record, index, 'source')
        },
        // 拖动元素经过的元素
        onDragover: event => {
          // 兼容 IE
          var ev = event || window.event
          // 阻止默认行为
          ev.preventDefault()
        },
        // 鼠标松开
        onDrop: async event => {
          // 兼容IE
          var ev = event || window.event
          // 阻止冒泡
          ev.stopPropagation()
          // 得到目标数据序号
          change2 = index
          // 这里就是让数据位置互换，让视图更新 你们可以看record，index的输出，看是什么
          //   const pre1 = data.sortList[change1].sortId
          //   const pre2 = data.sortList[change2].sortId

          //   // data.sortList[change1].sortId =  JSON.parse(JSON.stringify(pre2))
          //  data.sortList.map((m,index) => {
          //     if(index==change2){
          //       m.sortId = pre1
          //     }
          //     if(index==change1){
          //       m.sortId = pre2
          //     }
          //     return m
          //   })
          ;[data.sortList[change1], data.sortList[change2]] = [data.sortList[change2], data.sortList[change1]]
          // this.$set(data.sortList[change2], 'sortId',pre1)
          // delete  data.sortList[change2].sortId

          // if (change1 != change2) {
          //   api
          //     .serviceTypeSort({
          //       downOrUp: change1 > change2 ? 0 : 1,
          //       id: changeObj.id,
          //       targetId: record.id,
          //     })
          //     .then((r) => {
          //       if (r.success) {
          //         initChildrenList();
          //       }
          //     });
          // }

          console.log(record, index, 'target')
        }
      }
    }
    // 一级分类
    async function initServiceList() {
      let obj = {
        pageNum: 1,
        pageSize: 80
      }
      let res1 = await selectAllType(obj)
      if (res1.success) {
        // res1.object.records.map((el) => (el.isLeaf = false)); //id是string类型的
        // data.typeList = res1.object.records;
      }
    }
    async function initAllDetailList() {
      // let res = await selectAllDetail();
      // if (res.success) {
      //   data.detaiList = res.object;
      // }
    }

    const loadData = async selectedOptions => {
      console.log('点击了选择', selectedOptions)
      const targetOption = selectedOptions[selectedOptions.length - 1]
      targetOption.loading = true // load options lazily

      let obj = {
        pageNum: 1,
        pageSize: 80,
        typeId: selectedOptions[0].id
      }
      let res = await selectAllService(obj)
      if (res.success) {
        targetOption.loading = false
        res.object.records.map(el => (el.name = el.serveName))
        targetOption.children = res.object.records

        data.typeList = [...data.typeList]
      }
    }

    return {
      ...toRefs(data),
      saleStatusOptions,
      consumeOptions,
      searchRef,
      editorElem,
      modalTitle,
      formRef,
      rules,
      rules1,
      columns,
      pagination,
      title,
      labelCol: { style: { width: '150px' } },
      wrapperCol: { span: 14 },
      handleTableChange,
      search,
      add,
      del,
      addArticle,
      handleToTop,
      cancel,
      edit,
      rowSelection,
      changeStack,
      selectConsume,
      selectService,
      chooseStatus,
      selectType,
      loadData,
      uploadDetail_image,
      uploadDetail_imgPath,
      closeModal,
      reset,
      disabledDate,
      cancel1,
      sortColums,
      handleSave,
      customRow1
    }
  },

  components: {
    CheckOutlined,
    EditOutlined,
    ExclamationCircleOutlined,
    QuestionCircleOutlined,
    PlusOutlined
  }
}
</script>

<style scoped lang="less">
.act {
  color: #2a9d8f;
}
</style>
